package com.jielihaofeng.service;

import com.alibaba.fastjson.JSONObject;
import com.jielihaofeng.pojo.Forecast;
import com.jielihaofeng.pojo.MailPojo;
import com.jielihaofeng.pojo.Weather;
import com.jielihaofeng.pojo.WeatherResponse;
import com.jielihaofeng.util.OkHttpUtil;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.InternetAddress;
import java.util.Date;
import java.util.List;

/**
 * @description 天气邮件发送服务
 * @author Johnnie Wind
 * @date 2020/11/29 08:39
 */
@Service
public class WeatherEmailService {

    // 日志记录
    private final Logger logger = LoggerFactory.getLogger(WeatherEmailService.class);

    @Autowired
    private JavaMailSenderImpl mailSender;//注入邮件工具类

    @Value("${spring.mail.nickname}")
    private String nickname;

    @Value("${spring.mail.properties.from}")
    private String from;

    @Value("${spring.mail.properties.to}")
    private String to;

    // 天气城市名称
    private final String cityName = "深圳";
    // 天气接口url
    private final String url_prefix = "http://wthrcdn.etouch.cn/weather_mini?city=";

    public void sendEmail(){
        // 构建邮件对象
        MailPojo mailPojo = makeMailPojo();
        // 获取天气预报信息
        String weatherData = getWeatherData();
        // 解析、拼装天气信息
        resolveAndSetWeatherData(weatherData, mailPojo);
        // 发送邮件
        sendMail(mailPojo);
    }

    /**
     * @description 构建邮件对象
     * @author Johnnie Wind
     * @date 2020/11/28 23:03
     * @Param []
     * @return com.jielihaofeng.pojo.MailPojo
     */
    private MailPojo makeMailPojo() {
        MailPojo mailPojo = new MailPojo();
        mailPojo.setFrom(from);
        mailPojo.setTo(to);
        mailPojo.setCc(from);
        mailPojo.setBcc(from);
        return mailPojo;
    }

    /**
     * @description 请求天气接口，获取天气数据
     * @author Johnnie Wind
     * @date 2020/11/28 22:54
     * @Param []
     * @return java.lang.String
     */
    private String getWeatherData() {
        String url = url_prefix.concat(cityName);
        try {
            Response data = OkHttpUtil.getInstance().getData(url);
            String weather = data.body().string();
            return weather;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取天气数据异常：" + e.getMessage(), e.getCause());
            return "获取天气数据异常：" + e.getMessage();
        }
    }

    /**
     * @description 解析天气数据，拼装成邮件内容，填充邮件内容
     * @author Johnnie Wind
     * @date 2020/11/28 22:55
     * @Param [weatherData]
     * @return java.lang.String
     */
    private String resolveAndSetWeatherData(String weatherData, MailPojo mailPojo) {
        logger.info("开始解析天气数据：" + weatherData);
        JSONObject jsonObject = JSONObject.parseObject(weatherData);
        WeatherResponse weatherResponse = JSONObject.parseObject(weatherData, WeatherResponse.class);
        System.out.println(weatherResponse);
        Weather data = weatherResponse.getData();
        if (data != null) {
            List<Forecast> forecast = data.getForecast();
            String nowWendu = data.getWendu();
            String ganmao = data.getGanmao();
            Forecast todayWeather = forecast.get(0);
            String date = todayWeather.getDate(); // 28日星期六
            String type = todayWeather.getType(); // 多云
            String high = todayWeather.getHigh().split(" ")[1]; // 高温 22℃
            String low = todayWeather.getLow().split(" ")[1]; // 低温 15℃
            String fengxiang = todayWeather.getFengxiang(); // 东北风
            String fengli = todayWeather.getFengli().substring(9, 11); // <![CDATA[3级]]>
            System.out.println(weatherResponse);
            String subject = String.format("[%s]早安，今天是%s，现在温度%s°C，最高%s，最低%s，%s%s。", type, date, nowWendu, high, low, fengxiang, fengli);
            String text = subject + "\n" + ganmao;
            System.out.println("解析后标题：" + subject);
            System.out.println("解析后内容：" + text);
            // 填充mailPojo
            mailPojo.setSubject(subject);
            mailPojo.setText(text);
        }
        return weatherData;
    }


    /**
     * @description 发送邮件
     * @author Johnnie Wind
     * @date 2020/11/28 22:57
     * @Param []
     * @return void
     */
    private MailPojo sendMail(MailPojo mailPojo) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型
            InternetAddress internetAddress = new InternetAddress();
//            messageHelper.setFrom(mailPojo.getFrom());//邮件发信人
            messageHelper.setFrom(nickname+'<'+from+'>');
            messageHelper.setTo(mailPojo.getTo().split(","));//邮件收信人
            messageHelper.setSubject(mailPojo.getSubject());//邮件主题
            messageHelper.setText(mailPojo.getText());//邮件内容
            if (!StringUtils.isEmpty(mailPojo.getCc())) {//抄送
                messageHelper.setCc(mailPojo.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailPojo.getBcc())) {//密送
                messageHelper.setBcc(mailPojo.getBcc().split(","));
            }
            if (mailPojo.getMultipartFiles() != null) {//添加邮件附件
                for (MultipartFile multipartFile : mailPojo.getMultipartFiles()) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }
            if (mailPojo.getSentDate() != null) {//发送时间
                mailPojo.setSentDate(new Date());
                messageHelper.setSentDate(mailPojo.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
            mailPojo.setStatus("ok");
            logger.info("发送邮件成功:{} -> {}", from, to);
        } catch (Exception e) {
            e.printStackTrace();
            mailPojo.setStatus("error");
            mailPojo.setError(e.getMessage());
            logger.error("发送失败：" + e.getMessage(), e.getCause());
        }
        return mailPojo;
    }

    // 测试
    public static void main(String[] args) throws Exception {
        String url = "http://wthrcdn.etouch.cn/weather_mini?city=深圳";
        Response response = OkHttpUtil.getInstance().getData(url);
        String weatherData = response.body().string();
        WeatherResponse weatherResponse = JSONObject.parseObject(weatherData, WeatherResponse.class);
        System.out.println(weatherResponse);
        Weather data = weatherResponse.getData();
        if (data != null) {
            List<Forecast> forecast = data.getForecast();
            String nowWendu = data.getWendu();
            String ganmao = data.getGanmao();
            Forecast todayWeather = forecast.get(0);
            String date = todayWeather.getDate(); // 28日星期六
            String type = todayWeather.getType(); // 多云
            String high = todayWeather.getHigh().split(" ")[1]; // 高温 22℃
            String low = todayWeather.getLow().split(" ")[1]; // 低温 15℃
            String fengxiang = todayWeather.getFengxiang(); // 东北风
            String fengli = todayWeather.getFengli().substring(9, 11); // <![CDATA[3级]]>
            System.out.println(weatherResponse);
            String subject = String.format("[%s]早安，今天是%s，现在温度%s°C，最高%s，最低%s，%s%s。", type, date, nowWendu, high, low, fengxiang, fengli);
            String text = subject + "\n" + ganmao;
            System.out.println(subject);
            System.out.println(text);
        }

    }

}
